package handlers

import (
	"car-trade-sys/cache"
	"car-trade-sys/model"
	"car-trade-sys/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	redis_key := "login_" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "超过3次错误,封禁",
		})
		return
	}
	var user model.User
	model.DB.Where("username=?", username).Find(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if cacheData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "错误三次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return
}
func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	if uid == 0 || rid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	err := model.DB.Create(data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func RoleNodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var data []model.Node
	err := model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.rid=nodes.id").
		Where("role_nodes.rid=?", rid).
		Find(&data).
		Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	var data []model.Role
	err := model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.uid=roles.id").
		Where("user_roles.uid=?", uid).
		Find(&data).
		Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
func CarAdd(c *gin.Context) {
	carname := c.PostForm("carname")
	carprice, _ := strconv.Atoi(c.PostForm("carprice"))
	if carname == "" || carprice == 0 {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "不能为空",
		})
		return
	}
	data := model.Car{
		CarName:  carname,
		CarPrice: carprice,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func CarOrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	if order_code == "" || uid == 0 || cid == 0 {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "不能为空",
		})
		return
	}
	data := model.CarOrder{
		OrderCode: order_code,
		Uid:       uid,
		Cid:       cid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	if page == 0 || size == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	var data []model.CarOrderList
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_orders").
			Select(
				"car_orders.id AS OrderId",
				"car_orders.order_code AS OrderCode",
				"users.username AS Username",
				"cars.car_name AS CarName",
				"cars.car_price AS CarPrice",
			).
			Joins("JOIN cars ON car_orders.cid = cars.id").
			Joins("JOIN users ON car_orders.uid=users.id").
			Offset(offset).Limit(size).
			Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	var total int64
	model.DB.Table("car_orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  data,
		"total": total,
	})
}
func Del(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	redis_key := "list_" + strconv.Itoa(page)
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func CarOrderListId(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	if id == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	var data model.CarOrderList
	redis_key := "list_id_" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_orders").
			Select(
				"car_orders.id AS OrderId",
				"car_orders.order_code AS OrderCode",
				"users.username AS Username",
				"cars.car_name AS CarName",
				"cars.car_price AS CarPrice",
			).
			Joins("JOIN cars ON car_orders.cid = cars.id").
			Joins("JOIN users ON car_orders.uid=users.id").
			Where("car_orders.id=?", id).
			Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
}
